<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //函数记忆 函数优化  函数缓存
        var times = 0;

        function factorial(n) {
            times++;
            if (n === 0 || n === 1) {
                return 1;
            }
            return n * factorial(n - 1)
        }
        for (let i = 0; i <= 6; i++) {
            console.log(factorial(i));
        }
        console.log(times); //22
        var times1 = 0;
        cache = [];

        function factorial1(n) {
            times1++
            if (cache[n]) {
                return cache[n];
            }
            if (n === 0 || n === 1) {
                cache[0] = 1;
                cache[1] = 1
                return 1
            }
            return cache[n] = n * factorial1(n - 1)
        }
        for (let i = 0; i <= 6; i++) {
            console.log(factorial1(i));
        }
        console.log(times1); //12
        console.log('------------------');


        // 缓存函数
        function memorize(fn) {
            var cache = {};

            return function() {
                var k = arguments.length + [].join.call(arguments, ',')
                console.log(k);
                console.log(cache);
                return cache[k] = cache[k] || fn.apply(this, arguments)
            }
        }
        var f = memorize(factorial);
        console.log(f(6));
        console.log(f(5));
    </script>
</body>

</html>